package demo.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import demo.Result;
import demo.dto.RequestAskForJobDto;
import demo.dto.ResponseUserUserCompanyDto;
import demo.entity.Company;
import demo.entity.Seek;
import demo.entity.User;
import demo.entity.UserCompany;
import demo.repository.PMRepository;
import demo.service.*;
import demo.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户在职信息 Controller
 *
 * @author 肖溥博文
 * @version 1.3
 */
@RestController
public class UserCompanyController {

    @Autowired
    UserService userService;
    @Autowired
    UserCompanyService userCompanyService;
    @Autowired
    CompanyService companyService;
    @Autowired
    DepartmentService departmentService;
    @Autowired
    SeekService seekService;
    @Autowired
    PMService pmService;

    @PostMapping("/listUserCompany")
    public Result listUserCompany(@RequestBody User user) {
        if (userService.findUserByUid(user.getUid()) == null) {
            return Result.error("没有找到该用户");
        }

        List<ResponseUserUserCompanyDto> responseUserUserCompanyDtos = new ArrayList<>();
        List<UserCompany> userCompanyList = userCompanyService.listUserCompanies(user);

        for (UserCompany userCompany : userCompanyList) {
            ResponseUserUserCompanyDto responseUserUserCompanyDto = new ResponseUserUserCompanyDto();
            BeanUtil.copyProperties(userCompany, responseUserUserCompanyDto);
            responseUserUserCompanyDto.setBeginTime(DateUtil.formatToDay(userCompany.getBeginTime()));
            responseUserUserCompanyDto.setEndTime(DateUtil.formatToDay(userCompany.getEndTime()));
            BeanUtil.copyProperties(companyService.find(userCompany.getCompanyId()).getData(), responseUserUserCompanyDto);
            BeanUtil.copyProperties(departmentService.findByDepartmentId(userCompany.getDepartmentId()), responseUserUserCompanyDto);
            responseUserUserCompanyDtos.add(responseUserUserCompanyDto);
        }

        return Result.success("查询用户所有工作经历成功", responseUserUserCompanyDtos);
    }

    /**
     * 求职
     *
     * @param requestAskForJobDto 必须包含 uid 和 公司 id
     * @return 结果对象，若成功则包含 seek 对象
     */
    @PostMapping("/askForJob")
    public Result askForJob(@Validated @RequestBody RequestAskForJobDto requestAskForJobDto) {
        Long uid = requestAskForJobDto.getUid();
        User user = userService.findUserByUid(uid);
        if (user == null) {
            return Result.error("求职失败，用户不存在");
        }

        if (userCompanyService.findLatestUserCompanyByUid(uid).getCode() == 200) {
            return Result.error("求职失败，用户已在职");
        }

        Long companyId = requestAskForJobDto.getCompanyId();
        Result findCompanyResult = companyService.find(companyId);
        if (findCompanyResult.getCode() != 200) {
            return Result.error("求职失败，公司不存在");
        }

        // 尝试获取该公司的 HRs
        Result listHRResult = userCompanyService.listEmployeesByPosition(companyId, "HR");
        if (listHRResult.getCode() != 200) {
            throw new RuntimeException("异常：公司不存在或 HR 不存在，无法求职");
        }
        List<UserCompany> userCompanies = (List<UserCompany>) listHRResult.getData();

        // 当对该公司的邀请码已存在时，不添加新邀请码，而是重新发送已经生成的邀请码
        Result findExistingInvitingCode = seekService.findByUidAndCompanyId(uid, companyId);
        if (findExistingInvitingCode.getCode() == 200) {
            for (UserCompany userCompany : userCompanies) {
                pmService.sendPM(uid, userCompany.getUid(),
                    "我向你发起了一条求职请求，邀请码是 " + ((Seek) findExistingInvitingCode.getData()).getInvitingCode());
            }
            return Result.success("已经向该公司发送过邀请码");
        }

        // 尝试生成求职码
        Result generateSeekResult = seekService.save(uid, companyId);
        if (generateSeekResult.getCode() != 200) {
            return generateSeekResult;
        }
        Seek seek = (Seek) generateSeekResult.getData();

        // 发送求职请求
        for (UserCompany userCompany : userCompanies) {
            pmService.sendPM(uid, userCompany.getUid(),
                "我向你发起了一条求职请求，邀请码是 " + seek.getInvitingCode());
        }

        return generateSeekResult;
    }
}
